"use strict";

require.config({
    waitSeconds: 0,
});

define(['ajax', 'url'], function(ajax, url) {
    function overlay(show)
    {
        var cl = login.querySelector('.overlay').classList;
        if (show) cl.remove('hidden');
        else cl.add('hidden');
    }

    function show_error(error)
    {
        var e = login.querySelector('.error');
        var cl = e.classList;
        if (error == null)
            cl.remove('show');
        else {
            e.textContent = error;
            cl.add('show');
        }
    }

    function init()
    {
        var redirect = url.parse(location.href).args.redirect;
        if (redirect == null) return;
        overlay(false);

        login.onsubmit = function(ev) {
            ev.preventDefault();
            show_error(null);
            overlay(true);

            var username = login.querySelector('#username').value;
            var password = login.querySelector('#password').value;

            function fail(error)
            {
                if (error.startsWith("bad argument:"))
                    error = "用户名不存在";
                else if (error == "auth failed")
                    error = "密码错误";
                else {
                    console.error(error);
                    error = "服务器错误，请稍候重试";
                }
                overlay(false);
                show_error(error);
            }
            function ok(json)
            {
                var loc = url.parse(redirect);
                loc.args.name     = json.name;
                loc.args.username = username;
                location.href = url.build(loc.base, loc.args, "#" + json.token);
            }

            var query = url.build("../api/user/login", {
                username: username,
                password: password,
            });
            ajax.get_json(query, ok, fail);
        };
    }

    if (document.readyState === 'complete') init();
    else window.onload = init;
});

